package org.yuning.cloud.starter.configuration;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yuning.cloud.common.exception.ApiException;
import org.yuning.cloud.common.web.JsonResult;

/**
 * @author zhangzz
 * @email 291110369@qq.com
 * @date 2023/11/9 16:41
 * @description
 **/
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@RestControllerAdvice
public class RestApiExceptionHandler {

    private Logger log = LoggerFactory.getLogger(RestApiExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public JsonResult<String> exception(Exception exception) {
        log.error("Controller全局异常", exception);
        return JsonResult.fail(500, "系统内部异常", ExceptionUtils.getStackTrace(exception));
    }

    @ExceptionHandler(ApiException.class)
    public JsonResult<String> apiException(ApiException exception) {
        log.error("接口异常", exception);
        return JsonResult.fail(exception.getCode(), "接口异常", ExceptionUtils.getStackTrace(exception));
    }

}
